package com.hh.fudan.project_management;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.test.NotificationSpider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;

import com.hh.fudan.project_management.basic.Global;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.view.RenrenAuthListener;
import com.weibo.net.RequestToken;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class GroupShoppingActivity extends TabActivity {
	private Renren renren;
	private RenrenAuthListener listener;
	private Weibo mWeibo = Weibo.getInstance();
	private SharedPreferences prefs;
	TabHost tabHost; // The activity TabHost

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// start notification service;
		Intent intent2 = new Intent();
		intent2.setAction("com.service.notification");
		startService(intent2);

		renren = new Renren(Global.RENREN_API_KEY, Global.RENREN_SECRET_KEY,
				Global.RENREN_APP_ID, this);
		prefs = getSharedPreferences("usersettings", 0); 
		// login listener
		listener = new RenrenAuthListener() {
			@Override
			public void onComplete(Bundle values) {
				// 成功登录后，存入人人id和sessionKey
				// System.out.println("Complete.renren uid:"
				// + renren.getCurrentUid());
				// System.out.println("renren sessionKey:"
				// + renren.getSessionKey());
				Editor editor = prefs.edit();
				editor.putLong("UID_RENREN", renren.getCurrentUid());
				editor.putString("SESSION_KEY_RENREN", renren.getSessionKey());
				editor.commit();
				Toast.makeText(GroupShoppingActivity.this, "人人登录成功！",
						Toast.LENGTH_LONG).show();
			}

			@Override
			public void onRenrenAuthError(RenrenAuthError renrenAuthError) {
				Toast.makeText(
						GroupShoppingActivity.this,
						GroupShoppingActivity.this.getString(R.string.app_name),
						Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onCancelLogin() {
			}

			@Override
			public void onCancelAuth(Bundle values) {
			}

		};
		tabHost = getTabHost();
		tabHost.setup();
		// initButtons();
		Resources res = getResources(); // Resource object to get Drawables

		TabHost.TabSpec spec; // Resusable TabSpec for each tab
		Intent intent; // Reusable Intent for each tab

		// Create an Intent to launch an Activity for the tab (to be reused)
		intent = new Intent().setClass(this, ViewActivity.class);

		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost
				.newTabSpec("notification")
				.setIndicator("我的提醒",
						res.getDrawable(R.drawable.tab_notification))
				// .setIndicator("", null)
				.setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, NotificationViewActivity.class);
		spec = tabHost
				.newTabSpec("newNotification")
				.setIndicator("新的提醒",
						res.getDrawable(R.drawable.tab_new_notification))
				// .setIndicator("", null)
				.setContent(intent);
		tabHost.addTab(spec);

		// Do the same for the other tabs
		intent = new Intent().setClass(this, SearchActivity.class);
		spec = tabHost.newTabSpec("search")
				.setIndicator("搜   索", res.getDrawable(R.drawable.tab_search))
				// .setIndicator("", null)
				.setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, SettingsActivity.class);
		spec = tabHost
				.newTabSpec("settings")
				.setIndicator("设   置", res.getDrawable(R.drawable.tab_settings))
				// .setIndicator("", null)
				.setContent(intent);
		tabHost.addTab(spec);

		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
			tabHost.getTabWidget().getChildAt(i)
					.setBackgroundColor(Color.WHITE);
		}

		// tabHost.getTabWidget().getChildAt(0).setBackgroundDrawable(res.getDrawable(R.drawable.my_notification_dark));
		// tabHost.getTabWidget().getChildAt(1).setBackgroundDrawable(res.getDrawable(R.drawable.new_notification_dark));
		// tabHost.getTabWidget().getChildAt(2).setBackgroundDrawable(res.getDrawable(R.drawable.search_dark));
		// tabHost.getTabWidget().getChildAt(3).setBackgroundDrawable(res.getDrawable(R.drawable.settings_dark));
		tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.BLACK);
		tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.BLACK);
		tabHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.BLACK);
		tabHost.getTabWidget().getChildAt(3).setBackgroundColor(Color.BLACK);

		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {

					// View view = tabHost.getTabWidget().getChildAt(i);
					// final TextView tv =
					// (TextView)view.findViewById(R.id.title);
					// tv.setTextSize(20);
					// tv.setTextColor(Color.BLUE);
				}

				// tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.GRAY);
				// View view =
				// tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab());
				// final TextView tv = (TextView)view.findViewById(R.id.title);
				// tv.setTextColor(Color.YELLOW);
			}
		});
		// 从通知端进入应用
		if (this.getIntent() != null && this.getIntent().getData()!=null&&getIntent().getData().toString().equals("notif")) {
			Log.i("Enter From Notification:","notification");
			NotificationSpider.enterFromNotif = true;
		}
		tabHost.setCurrentTab(1);

		if(this.getIntent()!=null&&this.getIntent().getData()==null){
			tabHost.setCurrentTab(1);
		}
	}

	/** 微博登录，存入信息 */
	@Override
	public void onResume() {
		super.onResume();
		if (this.getIntent() != null && this.getIntent().getData()!= null&&!getIntent().getData().toString().equals("notif")) {
			Uri uri = this.getIntent().getData();
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");
			mWeibo.addOauthverifier(oauth_verifier);
			try {
				mWeibo.generateAccessToken(this, null);
			} catch (WeiboException e1) {
				e1.printStackTrace();
			}
			String url = Weibo.SERVER + "account/verify_credentials.json";
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("source", Weibo.APP_KEY);
			String rlt = null;
			try {
				rlt = mWeibo.request(this, url, bundle, "GET",
						mWeibo.getAccessToken());
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			String userId = rlt.substring(rlt.indexOf("id\":") + 4,
					rlt.indexOf(","));
			Log.i("userId", userId);
			Editor editor = prefs.edit();
			editor.putString("UID_WEIBO", userId);
			editor.commit();

			Toast.makeText(GroupShoppingActivity.this, "微博登录成功！",
					Toast.LENGTH_LONG).show();

		} else if (this.getIntent() != null) {

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		if (prefs.getLong("UID_RENREN", 0) == 0
				&& prefs.getString("UID_WEIBO", "").length() == 0) {
			menu.findItem(R.id.loginout).setTitle("登录");
		} else
			menu.findItem(R.id.loginout).setTitle("注销");
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		if (prefs.getLong("UID_RENREN", 0) == 0
				&& prefs.getString("UID_WEIBO", "").length() == 0) {
			menu.findItem(R.id.loginout).setTitle("登录");
		} else
			menu.findItem(R.id.loginout).setTitle("注销");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.new_notif:
			tabHost.setCurrentTab(1);
			return true;
		case R.id.all_notif:
			tabHost.setCurrentTab(2);
			return true;
		case R.id.search:
			tabHost.setCurrentTab(3);
			return true;
		case R.id.notif_setting:
			tabHost.setCurrentTab(4);
			return true;
		case R.id.upload_settings:
			uploadSettings();
			return true;
		case R.id.sync_settings:
			syncSettings();
			return true;
		case R.id.loginout:
			handleLoginout(item);
			return true;
		case R.id.exit:
			finish();
		}
		return false;
	}

	/** 上传设置 */
	private void uploadSettings() {
		if (prefs.getLong("UID_RENREN", 0) == 0
				&& prefs.getString("UID_WEIBO", "").length() == 0) {
			Toast.makeText(GroupShoppingActivity.this, "未登录！",
					Toast.LENGTH_LONG).show();
			return;
		}
		String cityName = prefs.getString("cityName", "");
		String title = prefs.getString("title", "");
		String price = prefs.getString("price", "");
		String discountPercent = prefs.getString("discountPercent", "");
		String members = prefs.getString("members", "0");
		String userId = "";
		int distance = prefs.getInt("distance", 0);

		if (prefs.getLong("UID_RENREN", 0) == 0)
			userId = prefs.getString("UID_WEIBO", "");
		else
			userId = prefs.getLong("UID_RENREN", 0) + "";
		HttpPost httpRequest = new HttpPost(Global.SERVER_USER_URL);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (cityName.length() > 0)
			params.add(new BasicNameValuePair("cityName", cityName));
		if (title.length() > 0)
			params.add(new BasicNameValuePair("title", title));
		if (price.length() > 0)
			params.add(new BasicNameValuePair("price", price));
		if (members.length() > 0)
			params.add(new BasicNameValuePair("members", members));
		if (userId.length() > 0)
			params.add(new BasicNameValuePair("userId", userId + ""));
		if (distance > 0)
			params.add(new BasicNameValuePair("distance", distance + ""));
		if (discountPercent.length() > 0)
			params.add(new BasicNameValuePair("discountPercent",
					discountPercent));
		System.out.println("城市名：" + cityName + " title:" + title + " price:"
				+ price + " discountPercent:" + discountPercent + "members:"
				+ members + "uid:" + userId);
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String rst = EntityUtils.toString(httpResponse.getEntity());
				Toast.makeText(GroupShoppingActivity.this, rst,
						Toast.LENGTH_LONG).show();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 同步设置 */
	private void syncSettings() {
		if (prefs.getLong("UID_RENREN", 0) == 0
				&& prefs.getString("UID_WEIBO", "").length() == 0) {
			Toast.makeText(GroupShoppingActivity.this, "未登录！",
					Toast.LENGTH_LONG).show();
			return;
		}
		String userId = "";
		if (prefs.getLong("UID_RENREN", 0) == 0)
			userId = prefs.getString("UID_WEIBO", "");
		else
			userId = prefs.getLong("UID_RENREN", 0) + "";
		String url = Global.SERVER_USER_URL + "?userId=" + userId;

		System.out.println("同步设置的url：" + url);

		Editor edit = prefs.edit();
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(url);
			Element root = doc.getRootElement();
			String cityName = root.getChildText("cityName");

			String title = root.getChildText("title");
			String price = root.getChildText("price");
			String members = root.getChildText("members");
			String discountPercent = root.getChildText("discountPercent");
			String distance = root.getChildText("distance");

			if (cityName != null && cityName.length() > 0) {
				edit.putString("cityName", cityName).commit();
			}
			if (title != null && title.length() > 0)
				edit.putString("title", title).commit();
			if (price != null && price.length() > 0)
				edit.putString("price", price).commit();
			if (members != null && members.length() > 0)
				edit.putString("members", members).commit();
			if (discountPercent != null && discountPercent.length() > 0)
				edit.putString("discountPercent", discountPercent).commit();
			if (distance != null && distance.length() > 0)
				edit.putInt("distance", Integer.parseInt(distance)).commit();
			Toast.makeText(GroupShoppingActivity.this, "同步账户成功！",
					Toast.LENGTH_LONG).show();
			System.out.println("存入的cityName：" + cityName + " title:" + title
					+ " price:" + price + " members:" + members
					+ " discountPercent:" + discountPercent);
		} catch (JDOMException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private void handleLoginout(final MenuItem item) {
		if (item.getTitle().equals("登录")) {
			new AlertDialog.Builder(GroupShoppingActivity.this)
					// build AlertDialog
					.setTitle("选择登录方式")
					// title
					.setItems(R.array.login_method,
							new DialogInterface.OnClickListener() { // content
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (which == 0)
										handleLoginout1(item);
									else if (which == 1)
										handleLoginout2(item);
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss(); // 关闭alertDialog
								}
							}).show();
		} else {
			// 注销
			if (prefs.getLong("UID_RENREN", 0) != 0) {
				handleLoginout1(item);
			} else if (prefs.getString("UID_WEIBO", "").length() > 0) {
				handleLoginout2(item);
			}
		}

	}

	private void handleLoginout1(MenuItem item) {
		if (prefs.getLong("UID_RENREN", 0) == 0) {
			renren.authorize(GroupShoppingActivity.this, listener);
		} else {
			renren.logout(GroupShoppingActivity.this);
			Editor editor = prefs.edit();
			editor.putLong("UID_RENREN", 0);
			editor.putString("SESSION_KEY_RENREN", "");
			editor.commit();
			Toast.makeText(GroupShoppingActivity.this, "人人用户已注销！",
					Toast.LENGTH_LONG).show();
		}
	}

	private void handleLoginout2(MenuItem item) {
		if (prefs.getString("UID_WEIBO", "").length() == 0) {
			// 登录
			mWeibo.setupConsumerConfig(Global.WEIBO_CONSUMER_KEY,
					Global.WEIBO_CONSUMER_SECRET);

			RequestToken requestToken = null;
			try {
				requestToken = mWeibo.getRequestToken(
						GroupShoppingActivity.this, Weibo.APP_KEY,
						Weibo.APP_SECRET, Global.WEIBO_URL_ACTIVITY_CALLBACK);

			} catch (WeiboException e) {
				e.printStackTrace();
			}
			Uri uri = Uri.parse(Weibo.URL_AUTHENTICATION
					+ "?display=wap2.0&oauth_token=" + requestToken.getToken()
					+ "&from=xweibo");
			startActivity(new Intent(Intent.ACTION_VIEW, uri));
		} else {
			// 注销
			Editor editor = prefs.edit();
			editor.putString("UID_WEIBO", "");
			editor.commit();
			Toast.makeText(GroupShoppingActivity.this, "微博用户已注销！",
					Toast.LENGTH_LONG).show();
		}
	}

}